﻿/**********************************************************************************
 * 程序说明：     数据库助手类(简单型无参数)
 * 创建日期：     2009.10.20
 * 程序制作：     agui
 * 联系方式：     mailto: 35499039 3@qq.com  
 * ********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using PlugNT.Safe;
using PlugNT.Database.Common;

namespace PlugNT.Database.Common.Entity
{
    /// <summary>
    /// 数据库帮助类（需要修改，重载Complex即可）
    /// </summary>
    public class DbHelper
    {
        public DbInfo dbinfo;
        private DbConnection connection;
        private DbDataAdapter dadapter;

        public DbHelper()
        {
            dbinfo = new DbInfo(IConfig.DbType, IConfig.ConnectionString);
            Init(dbinfo);
        }
        public DbHelper(DbInfo dbInfo)
        {
            Init(dbInfo);
        }
        private void Init(DbInfo dbInfo)
        {
            dbinfo = dbInfo;
            connection = DbProvider.CreateConnection(dbinfo);
            connection.Open();
            dadapter = DbProvider.GetFactory(dbinfo).CreateDataAdapter();
        }

        ~DbHelper()
        {
            //出错：.Net Framework 数据提供程序错误
            //if (connection != null && connection.State == ConnectionState.Open)  
            //{
            //    connection.Close();
            //}
            connection = null;
        }

        /// <summary>
        /// 保持连接状态
        /// </summary>
        private void OpenConnection()
        {
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void CloseConnection()
        {
            if (connection.State != ConnectionState.Closed)
            {
                connection.Close();
            }
        }

        #region 公用方法
        /// <summary>
        /// 判断是否存在某表的某个字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="columnName">列名称</param>
        /// <returns>是否存在</returns>
        public bool ColumnExists(string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id('" + StringHelper.SqlFilter(tableName) + "') and [name]='" + StringHelper.SqlFilter(columnName) + "'";
            object res = GetSingle(sql);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }

        public int GetMaxID(string FieldName, string TableName)
        {
            string strsql = "select max(" + StringHelper.SqlFilter(FieldName) + ")+1 from " + StringHelper.SqlFilter(TableName);
            object obj = GetSingle(strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }
        /// <summary>
        /// 表是否存在
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public bool TabExists(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N'[" + StringHelper.SqlFilter(TableName) + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
            object obj = GetSingle(strsql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public bool Exists(string strSql)
        {
            object obj = GetSingle(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public bool Exists(string strSql, params DbParameter[] cmdParms)
        {
            object obj = GetSingle(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string SQLString)
        {
            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();

                cmd.Connection = connection;
                cmd.CommandText = SQLString;

                object obj = cmd.ExecuteScalar();

                cmd.Dispose();
                cmd = null;
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (DbException ex)
            {
                connection.Close();
                throw ex;
            }

        }
        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public object GetSingle(string SQLString, params DbParameter[] cmdParms)
        {
            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();

                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                object obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();

                cmd.Dispose();
                cmd = null;
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }
            catch (DbException e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 重置表
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="tabName"></param>
        /// <param name="idName"></param>
        /// <returns></returns>
        public bool ReSetTable(string tabName, string idName)
        {
            ExecuteSql("delete from " + StringHelper.SqlFilter(tabName));
            return (ExecuteSql(Tables.GetReSetTableStr(dbinfo, tabName, idName)) > 0) ? true : false;
        }
        #endregion

        #region  执行简单SQL语句
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString)
        {

            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();
                cmd.Connection = connection;
                cmd.CommandText = SQLString;

                int rows = cmd.ExecuteNonQuery();

                cmd.Dispose();
                cmd = null;
                return rows;
            }
            catch (DbException ex)
            {
                connection.Close();
                throw ex;
            }

        }
        public int ExecuteSqlByTime(string SQLString, int Times)
        {

            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();
                cmd.Connection = connection;
                cmd.CommandText = SQLString;

                cmd.CommandTimeout = Times;
                int rows = cmd.ExecuteNonQuery();

                cmd.Dispose();
                cmd = null;
                return rows;
            }
            catch (DbException ex)
            {
                connection.Close();
                throw ex;
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public int ExecuteSqlTran(List<String> SQLStringList)
        {
            OpenConnection();
            DbCommand cmd = connection.CreateCommand();
            cmd.Connection = connection;

            DbTransaction tx = connection.BeginTransaction();
            cmd.Transaction = tx;
            try
            {
                int count = 0;
                for (int n = 0; n < SQLStringList.Count; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Trim().Length > 1)
                    {
                        cmd.CommandText = strsql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                tx.Commit();
                cmd.Dispose();
                cmd = null;
                return count;
            }
            catch
            {
                tx.Rollback();
                return 0;
            }

        }

        /// <summary>
        /// 执行查询语句，返回DbDataReader ( 注意：调用该方法后，一定要对DbDataReader进行Close )
        /// </summary>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public DbDataReader ExecuteReader(string SQLString)
        {
            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();
                cmd.Connection = connection;
                cmd.CommandText = SQLString;

                DbDataReader myReader = cmd.ExecuteReader();

                cmd.Dispose();
                cmd = null;
                return myReader;
            }
            catch (DbException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string SQLString)
        {
            return Query(SQLString).Tables[0];
        }
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string SQLString)
        {

            DataSet ds = new DataSet();
            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();

                cmd.CommandText = SQLString;
                dadapter.SelectCommand = cmd;

                cmd.Dispose();
                cmd = null;
                dadapter.Fill(ds);
            }
            catch (DbException ex)
            {
                throw new Exception(ex.Message);
            }
            return ds;

        }
        #endregion

        #region 执行带参数的SQL语句

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public int ExecuteSql(string SQLString, params DbParameter[] cmdParms)
        {

            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                int rows = cmd.ExecuteNonQuery();

                cmd.Dispose();
                cmd = null;
                return rows;
            }
            catch (DbException e)
            {
                throw e;
            }

        }

        /// <summary>
        /// 执行查询语句，返回DbDataReader ( 注意：调用该方法后，一定要对DbDataReader进行Close )
        /// </summary>
        /// <param name="SQLString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public DbDataReader ExecuteReader(string SQLString, params DbParameter[] cmdParms)
        {

            try
            {
                OpenConnection();
                DbCommand cmd = connection.CreateCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);

                DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                cmd.Dispose();
                cmd = null;

                return myReader;
            }
            catch (DbException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string SQLString, params DbParameter[] cmdParms)
        {
            OpenConnection();
            DbCommand cmd = connection.CreateCommand();
            PrepareCommand(cmd, connection, null, SQLString, cmdParms);

            dadapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            try
            {
                dadapter.Fill(ds, "ds");

                cmd.Dispose();
                cmd = null;
            }
            catch (DbException ex)
            {
                throw new Exception(ex.Message);
            }
            return ds;

        }


        private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (DbParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 存储过程操作（限于sql server）

        /// <summary>
        /// 执行存储过程，返回SqlDataReader ( 注意：调用该方法后，一定要对SqlDataReader进行Close )
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public DbDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            OpenConnection();
            DbDataReader returnReader;
            DbCommand cmd = connection.CreateCommand();

            cmd.Parameters.Clear();
            BuildQueryCommand(cmd, storedProcName, parameters);
            cmd.CommandType = CommandType.StoredProcedure;
            returnReader = cmd.ExecuteReader();

            cmd.Dispose();
            cmd = null;

            return returnReader;
        }


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            OpenConnection();
            DataSet dataSet = new DataSet();
            DbCommand cmd = connection.CreateCommand();

            cmd.Parameters.Clear();
            BuildQueryCommand(cmd, storedProcName, parameters);
            dadapter.SelectCommand = cmd;
            dadapter.Fill(dataSet, tableName);

            cmd.Dispose();
            cmd = null;

            return dataSet;
        }

        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
            OpenConnection();
            DataSet dataSet = new DataSet();
            DbCommand cmd = connection.CreateCommand();

            cmd.Parameters.Clear();
            BuildQueryCommand(cmd, storedProcName, parameters);
            dadapter.SelectCommand = cmd;
            dadapter.SelectCommand.CommandTimeout = Times;
            dadapter.Fill(dataSet, tableName);

            cmd.Dispose();
            cmd = null;

            return dataSet;
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private void BuildQueryCommand(DbCommand cmd,  string storedProcName, IDataParameter[] parameters)
        {
            cmd.CommandText = storedProcName;
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (DbParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        /// <summary>
        /// 执行存储过程，返回影响的行数		
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            OpenConnection();
            int result;
            DbCommand cmd = connection.CreateCommand();

            cmd.Parameters.Clear();
            BuildIntCommand(cmd, connection, storedProcName, parameters);
            rowsAffected = cmd.ExecuteNonQuery();
            result = (int)cmd.Parameters["ReturnValue"].Value;

            cmd.Dispose();
            cmd = null;

            return result;
        }

        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)	
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private void BuildIntCommand(DbCommand cmd, DbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            BuildQueryCommand(cmd, storedProcName, parameters);
            DbParameter dbpar = DbProvider.MakeIntParam(dbinfo, "ReturnValue");
            dbpar.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(dbpar);
        }
        #endregion

        #region contact me
        public static string Help()
        {
            return @"mailto:354990393@qq.com";
        }
        #endregion
    }
}
